package com.study.patterns.proxy.dynamic.cglib;


import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.objectweb.asm.ClassWriter;

import java.io.FileOutputStream;
import java.lang.reflect.Method;

/**
 * Created by tan on 2017/6/20.
 */
public class ServiceInterceptorImpl implements MethodInterceptor {
    private Object target;
    private Enhancer enhancer;

    public Object getProxy(Object target) {
        this.target = target;
        enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        //enhancer.generateClass();

        return enhancer.create();
    }

    public void generateProxyClass() throws Exception {
        ClassWriter cw = new ClassWriter(0);
        enhancer.generateClass(cw);
        FileOutputStream outputStream = new FileOutputStream("cglibproxyclass.class");
        outputStream.write(cw.toByteArray());
    }

    @Override
    public Object intercept(Object object, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("前置代理");
        //通过代理类调用父类中的方法
        //Object result = methodProxy.invokeSuper(object, objects);
        Object result = method.invoke(target, objects);
        System.out.println("后置代理");
        return result;
    }
}
